package com.alinesno.cloud.portal.desktop.web.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alinesno.cloud.common.core.service.impl.IBaseServiceImpl;
import com.alinesno.cloud.portal.desktop.web.entity.LinkPathEntity;
import com.alinesno.cloud.portal.desktop.web.entity.UserFunctionEntity;
import com.alinesno.cloud.portal.desktop.web.repository.UserFunctionRepository;
import com.alinesno.cloud.portal.desktop.web.service.ILinkPathService;
import com.alinesno.cloud.portal.desktop.web.service.IUserFunctionService;

/**
 * <p>  服务实现类 </p>
 *
 * @author WeiXiaoJin
 * @since 2019-06-21 19:03:36
 */
@Service
public class UserFunctionServiceImpl extends IBaseServiceImpl< UserFunctionEntity, String> implements IUserFunctionService {

	//日志记录
	private static final Logger log = LoggerFactory.getLogger(UserFunctionServiceImpl.class);

	@Autowired
	private ILinkPathService linkPathService ; 
	
	@Autowired
	private UserFunctionRepository userFunctionRepository ; 
	
	@Transactional
	@Override
	public boolean updateFunctions(String id, String rolesId) {
		log.debug("id:{} , rolesId:{}" , id , rolesId);
		
		// 删除所有用户功能
		userFunctionRepository.deleteByUid(id) ; 

		List<UserFunctionEntity> fs = new ArrayList<UserFunctionEntity>() ; 
		
		String roleArr[] = rolesId.split(",") ; 
		for(String r : roleArr) {
			Optional<LinkPathEntity> lp = linkPathService.findById(r) ; 
			if(lp.isPresent()) {
				LinkPathEntity l = lp.get() ; 
				
				UserFunctionEntity u = new UserFunctionEntity() ; 
				
				u.setFunctionName(l.getLinkName());
				u.setFunctionDesc(l.getLinkDesc());
				u.setFunctionLogo(l.getLinkLogo());
				u.setFunctionPath(l.getLinkPath());
				u.setOpenTarget(l.getLinkTarget());
				
				u.setLid(l.getId());
				u.setUid(id);
				u.setFunctionSort(0);

				fs.add(u) ; 
			}
		}
		
		jpa.saveAll(fs) ;
		return true ;
	}

	@Override
	public List<UserFunctionEntity> findAllByUid(String id) {
		return userFunctionRepository.findAllByUid(id) ;
	}

}
